﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Security;
using System.Text;
using System.Web;
using System.Web.Configuration;

namespace WFramework.WebHelper
{
    /// <summary>
    /// web.config加密解密类，参考http://www.cnblogs.com/Gyoung/p/3194467.html
    /// </summary>
    public class WebConfigCrypt
    {
        //如果我们想用DataProtectionConfigurationProvider来实现加密与解密，只需在代码中将RSAProtectedConfigurationProvider替换成DataProtectionConfigurationProvider即可。
        //provider的值是：RSAProtectedConfigurationProvider 或DataProtectionConfigurationProvider

        private static readonly string section = "connectionStrings";

        public static void Encrypt(string provider)
        {
            Configuration confg = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            ConfigurationSection configSect = confg.GetSection(section);
            if (configSect != null)
            {
                configSect.SectionInformation.ProtectSection(provider);
                confg.Save();
            }
        }

        public static void Decrypt(string provider)
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            ConfigurationSection configSect = config.GetSection(section);
            if (configSect.SectionInformation.IsProtected)
            {
                configSect.SectionInformation.UnprotectSection();
                config.Save();
            }
        }
    }
}
